package com.kproduce.roundcorners;

import com.kproduce.roundcorners.util.RoundHelper;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Path;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.utils.Color;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

public class CircleImageView extends Image implements Component.DrawTask {
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00200, "CircleImageView");

    private Paint mPaint;

    private Path mPath;

    private double mStrokeWidth;

    private RectFloat rectFloat;

    private float mStrokeRadii[];

    private Color mColor;

    public CircleImageView(Context context) {
        super(context);
    }

    public CircleImageView(Context context, AttrSet attrSet) {
        super(context, attrSet);
        init(attrSet);
    }

    public CircleImageView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    private void init(AttrSet attrSet) {
        mStrokeRadii = new float[8];
        mPaint = new Paint();
        mPath = new Path();
        mColor = Color.RED;
        rectFloat = new RectFloat();
        mStrokeWidth = 10;
    }

    public void createCircleImage(int resId) {
        setPixelMap(resId);
        setClipGravity(GRAVITY_CENTER);
        float radius = (float) (Math.min(getHeight(), getWidth()) * 1f / 2 - mStrokeWidth);
        mStrokeRadii[0] = mStrokeRadii[1] = radius;
        mStrokeRadii[2] = mStrokeRadii[3] = radius;
        mStrokeRadii[4] = mStrokeRadii[5] = radius;
        mStrokeRadii[6] = mStrokeRadii[7] = radius;
        setCornerRadii(mStrokeRadii);
        setScaleMode(ScaleMode.CLIP_CENTER);
        invalidate();
    }

    private void drawLineWhitStroke(Canvas canvas, int width, int height, Color color) {
        mPaint.setStyle(Paint.Style.STROKE_STYLE);
        mPaint.setStrokeWidth((float) mStrokeWidth);
        mPaint.setColor(color);
        mPath.reset();
        rectFloat.fuse((float)(mStrokeWidth / 2), (float)(mStrokeWidth / 2), (float)(width - mStrokeWidth / 2), (float) (height - mStrokeWidth / 2));
        mPath.addRoundRect(rectFloat, mStrokeRadii, Path.Direction.COUNTER_CLOCK_WISE);
        canvas.drawPath(mPath, mPaint);
    }

    public void changeColor(Color color) {
        this.mColor = color;
        invalidate();
    }

    public void changeStrokeWidth(int strokeWidth) {
        this.mStrokeWidth = strokeWidth;
        invalidate();
    }

    @Override
    public void invalidate() {
        addDrawTask(this::onDraw);
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        drawLineWhitStroke(canvas, component.getWidth(), component.getHeight(), mColor);
    }
}